package com.xwltz.web.advice;

import com.xwltz.core.defines.Api;
import com.xwltz.core.domain.ActionResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

@RestControllerAdvice
public class ResultAdvice implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter methodParameter, @Nullable Class<? extends HttpMessageConverter<?>> aClass) {
		Method method = methodParameter.getMethod();
		if (method == null) {
			return false;
		}
		Api api = method.getAnnotation(Api.class);
		if (api == null || !api.needPackage()) {
			return false;
		}
		return !Void.class.equals(method.getReturnType());
	}

	@Override
	public Object beforeBodyWrite(Object o, MethodParameter methodParameter, @Nullable MediaType mediaType, @Nullable Class<? extends HttpMessageConverter<?>> aClass, @Nullable ServerHttpRequest serverHttpRequest, @Nullable ServerHttpResponse serverHttpResponse) {
		String message = "成功";
		Method method = methodParameter.getMethod();
		if (method != null) {
			Api api = method.getAnnotation(Api.class);
			RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
			if (api != null) {
				if ("".equals(api.resultMsg())) {
					message = api.name() + message;
				} else {
					message = api.resultMsg();
				}

			} else if (requestMapping != null) {
				message = requestMapping.name() + message;
			}
		}

		return ActionResult.success(message, o);
	}
}
